/* 移动动画 */
//obj-执行动画对象, attr-执行目标样式, target-目标位置, speed-速度, callback-回调函数,结束后执行
function move(obj, attr, speed, target, callback) {
    clearInterval(obj.timer);
    let current = parseInt(getComputedStyle(obj, null)[attr]);
    if (current > target) {
        speed = -speed;
    }
    //向obj添加属性，每个obj有单独的定时器，timer私有化
    obj.timer = setInterval(() => {
        let oldValue = parseInt(getComputedStyle(obj, null)[attr]);
        let newValue = oldValue + speed;
        if ((speed > 0 && newValue > target) || (speed < 0 && newValue < target))
            newValue = target;
        obj.style[attr] = newValue + "px";
        if (newValue == target) {
            clearInterval(obj.timer);
            callback && callback(); //存在callback时调用
        }
    }, 20);
}

/* 样式类各种操作 */
function addClass(obj, cn){
    if (!hasClass(obj, cn)) {
        obj.className += " " + cn;
    }
}
function removeClass(obj, cn){
    let reg = new RegExp("\\b" + cn + "\\b", "g");
    obj.className = obj.className.replace(reg, "");
}
/* 
    toggleClass切换类
    具有该类则删除，没有该类则添加
 */
function toggleClass(obj, cn){
    if(hasClass(obj, cn)){
        removeClass(obj, cn);
    }
    else {
        addClass(obj, cn);
    }
}
function hasClass(obj, cn){
    let reg = new RegExp("\\b" + cn + "\\b", "g");
    return reg.test(obj.className);
}